use openssl::pkey::{PKey, Private, Public};
use openssl::rsa::Rsa;
use crate::AppResult;
use tokio::fs::File;
use tokio::io::{AsyncReadExt};

pub mod agent;
pub mod certificate;
pub mod license_gen;
pub mod plugins;
pub mod products;

pub async fn get_file_or_create(path: &str) -> AppResult<File> {
    if tokio::fs::try_exists(path).await? {
        let file = File::options()
            .write(true)
            .read(true)
            .open(path).await?;
        Ok(file)
    }else{
        let file = File::options()
            .create(true)
            .write(true)
            .read(true)
            .truncate(true)
            .open(path)
            .await?;
        Ok(file)
    }
}
pub fn generate_rsa_key_pair(bit_size:u32) -> AppResult<(PKey< Private>, PKey<Public>)> {
    let pri_key = PKey::from_rsa(Rsa::generate(bit_size)?)?;
    let pub_key = PKey::public_key_from_der(pri_key.public_key_to_der()?.as_ref())?;
    Ok((pri_key, pub_key))
}

pub async  fn read_to_string(file: &mut File) -> AppResult<String> {
    let mut string = String::new();
    if file.metadata().await?.len()>0 {
        file.read_to_string(&mut string).await?;
    }
    Ok(string)
}

